<?php
// require_once 'base_controller.php';
// require_once 'common.php';

class friendship_controller extends base_controller
{
        
    public function dowork()
    {
        $msg_response = new message(WARNING_query_failed, 0, STR_text);      
        
        try 
        {
            switch ($this->method)
            {
                //获取所有用户信息列表
                case 'friends':
                    {
                        if(!isset($this->parameters['id']))
                            throw new Exception(warning_parameter_needed('id'));
            
                        $id = addslashes(trim($this->parameters['id']));    //$this->current_id
                        
                        $friends = self::get_friends($id);                        
                        $msg_response = new message($friends, 1, STR_array);                        
                    }
                    break;
                    
                case 'myfriends':
                    {
                        $id = $this->current_id;
                        
                        $friends =self::get_friends($id);
                        $msg_response = new message($friends, 1, STR_array);
                    }
                    break;
            
                case 'isfriend':
                    {
                        if(!isset($this->parameters['id']))
                            throw new Exception(warning_parameter_needed(warning_parameter_invalid('id')));
                        
                        if(!isset($this->parameters['id_query']))
                            throw new Exception(warning_parameter_needed('id_query'));            

                        $id = addslashes(trim($this->parameters['id']));
                        $id_query = addslashes(trim($this->parameters['id_query']));
                        
                        $isfriend = self::is_friend($id, $id_query);
                        $msg_response = new message($isfriend, 1, STR_boolean);
                        
                    }
                    break;
                    
                case 'friendship':
                    {
                        $id = $this->parameters['id'];
                        $id_query = $this->parameters['id_query'];
                        
                        $id = addslashes(trim($this->parameters['id']));
                        $id_query = addslashes(trim($this->parameters['id_query']));
                        
                        $friendship = self::get_friendship($id, $id_query);
                        
                        $msg_response = new message($friendship, 1, STR_object);                
                    }
                    break;
            
                case 'ask_friend':
                    {
                        if(!isset($this->parameters['id_toaccept']))
                            throw new Exception(warning_parameter_needed('id_toaccept'));
                        
                        $id_toaccept = addslashes(trim($this->parameters['id_toaccept']));
                        
                        $affected_row = self::ask_friend($this->current_id, $id_toaccept);
                        
                        if($affected_row)
                        {
                            $msg_response = new message(array('succeed'=>true, 'id_toaccept'=>$id_toaccept), 1, STR_boolean);
                        }
                        else 
                        {
                            $msg_response = new message(array('succeed'=>false, 'id_toaccept'=>$id_toaccept), 0, STR_boolean);
                        }                        
                    }
                    break;
            
                case 'friend_requests':
                    {
                        $requests = self::get_requests($this->current_id);
                        
//                         $length = count($requests);
//                         for($line = 0; $line<$length; $line++)
//                         {
//                             $requests[$line]['nickname_ask']=user_controller::get_user($requests[$line]['userask'])->nickname;
//                             $requests[$line]['nickname_accept']=user_controller::get_user($requests[$line]['useraccept'])->nickname;
                            
//                             if($requests[$line]['useraccept']===$this->current_id)
//                                 $requests[$line]['is_toaccept']=true;
//                             else 
//                                 $requests[$line]['is_toaccept']=false;
//                         }

                        $msg_response = new message($requests, 1, STR_array);
                    }
                    break;
                    
                case 'accept_friend':
                    {
                        if(!isset($this->parameters['id_ask']))
                            throw new Exception(warning_parameter_needed('id_ask'));
                        
                        $id_ask = addslashes(trim($this->parameters['id_ask']));
                        $id_toaccept = $this->current_id;
                        
                        $succeed = self::accept_friend($id_ask, $id_toaccept);
                        
                        if($succeed)
                            $msg_response = new message(array('succeed'=>true, 'id_toaccept'=>$id_toaccept, 'id_ask'=>$id_ask), 1, STR_boolean);
                        else 
                            $msg_response = new message(array('succeed'=>false, 'id_toaccept'=>$id_toaccept, 'id_ask'=>$id_ask), 0, STR_boolean);
                    }
                    break;
                    
                case 'delete_friend':
                    {
                        if(!isset($this->parameters['id_todelete']))
                            throw new Exception(warning_parameter_needed('id_todelete'));
                        
                        $id_todelete = addslashes(trim($this->parameters['id_todelete']));
                        $id_my = $this->current_id;
                        
                        $result = self::delete_friend($id_todelete, $id_my);
                        
                        if($result)
                        {
                            $msg_response = new message(array('succeed'=>true, 'id_todelete'=>$id_todelete), 1, STR_object);
                        }
                        else 
                        {
                            $msg_response = new message(array('succeed'=>false, 'id_todelete'=>$id_todelete), 0, STR_object);
                        }
                    }
                    break;
                    
                default:
                    {
                        $msg_response->content = warning_parameter_invalid('method', $this->method);
                    }
                    break;            
            }
        } 
        catch (Exception $e) 
        {
            $msg_response->content = $e->getMessage();
        }
        
        return $msg_response;
    }
    
    /**
     * 根据$id获取用户的朋友用户信息
     * @param unknown $id 
     * @return Ambigous <NULL, unknown> 返回的用户信息为对象数组形式，各对象中包含了id,nickname,isfriend三个属性，其中isfriend属性值都为“1”
     */
    public static function get_friends($id)
    {
        $db = db_connect();
        
        $str_query = "select users.id, users.nickname, '1' as isfriend from users where id in (".
            "select useraccept as id from friendship where userask = '".$id."' union ".
            "select userask as id from friendship where useraccept = '".$id."'"
            .");" ;
            
        $result = $db->query($str_query);
                
        db_is_result_succeed($result, $db);        
        
        $friends = dbresult_to_objects_array($result);
        
        return $friends;
    }
    
    /**
     * 判断两用户是否为朋友关系
     * @param unknown $id1
     * @param unknown $id2
     * @return boolean 是否为朋友关系
     */
    public static function is_friend($id1, $id2)
    {
        $friendship = self::get_friendship($id1, $id2);
        
        return !empty($friendship); 
    }
    
    /**
     * 获取两用户的朋友关系
     * @param unknown $id1
     * @param unknown $id2
     * @return unknown 返回为对象
     */
    public static function get_friendship($id1, $id2)
    {
        $db = db_connect();
        
        $str_query = 
            "select * from friendship where userask = '".$id1."' and useraccept = '".$id2."' or userask = '".$id2."' and useraccept = '".$id1."'" ;
        
        $result = $db->query($str_query);
        
        db_is_result_succeed($result, $db);
        
        $result = $result->fetch_object();
        
        return $result;        
    }

    
    public static function ask_friend($id_ask, $id_toaccept)
    {
        $is_friend=friendship_controller::is_friend($id_ask, $id_toaccept);
        
        if(!empty($is_friend))
        {
            throw new Exception(WARNING_already_friend);
        }
        
        $db = db_connect();
        
        $str_query =
            "insert into pending_friendship values('".$id_ask."','".$id_toaccept."','".datetime_now()."')";

        
        $result = $db->query($str_query);
        
        db_is_result_succeed($result, $db);

        return $db->affected_rows;
        //return $result;
    }
    
    public static function accept_friend($id_ask, $id_toaccept)
    {
        //先检查当前用户是否为$id_toaccept. 待提至调用处前
        if(!user_controller::is_current_user($id_toaccept))
        {
            throw new Exception(WARNING_unauthorized);
        }
        
        $is_friend=friendship_controller::is_friend($id_ask, $id_toaccept);
    
        if(!empty($is_friend))
        {
            throw new Exception(WARNING_already_friend);
        }
    
        $db = db_connect();
    
        //先查找是否存在相应的朋友请求
        $str_query =
            "select * from pending_friendship where userask = '".$id_ask."' and useraccept = '".$id_toaccept."'";    
        $result = $db->query($str_query);
        db_is_result_succeed($result, $db);
        
        if($result->num_rows == 0)
            throw new Exception("There is no corresponding friend request to accept. 'id_ask': ".$id_ask.", 'id_toaccept': ".$id_toaccept.".");
        
        //没抛出异常，表示存在相应的请求。 需要把相应的请求转移到friendship表格， 再在pending_friendship中删除
        $str_query =
            "insert into friendship values('".$id_ask."','".$id_toaccept."','".datetime_now()."')";
        $result = $db->query($str_query);        
        db_is_result_succeed($result, $db);
        
        //删除相应的请求……
        $str_query =
            "delete from pending_friendship where userask = '".$id_ask."' and useraccept = '".$id_toaccept."' or userask = '".$id_toaccept."' and useraccept = '".$id_ask."'" ;
        $result = $db->query($str_query);
        
        if(!$result)
        {
            $db->rollback();
            throw new Exception(WARNING_query_failed);
        }
        
        return $result;
    }
        
    
    public static function get_requests($id)
    {
        $db = db_connect();
     
        $str_query = //"select * from pending_friendship where useraccept = '".$id."' union all ".  "select * from pending_friendship where  userask ='".$id."'";
            "select users.id, users.nickname, '1' as isAskedFriend from users"
            ." where users.id in ("
            ."select pending_friendship.userask from pending_friendship where pending_friendship.useraccept = '".$id."');"
            ;
        
        $result = $db->query($str_query);
                
        db_is_result_succeed($result, $db);
        
        return dbresult_to_objects_array($result);
    }
    
    public static function delete_friend($id_todelete, $id_my)
    {
        $db = db_connect();
        
        $str_query = "delete from friendship where useraccept = '".$id_todelete."' and userask = '".$id_my."' or useraccept = '".$id_my."' and userask = '".$id_todelete."';";
        
        $result = $db->query($str_query);
        
        db_is_result_succeed($result, $db);
        
        return $db->affected_rows;
    }
    
    
    
}


?>